package com.tfswx.jcyw.ruleenginedesigner.service.impl;

import com.tfswx.ruleengine.compute.exception.AppException;
import com.tfswx.jcyw.ruleenginedesigner.dto.sjk.DataQueryInputDTO;
import com.tfswx.jcyw.ruleenginedesigner.service.SjkService;
import org.springframework.stereotype.Service;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Ricky
 * @date 2021/6/16
 */
@Service
public class SjkServiceImpl implements SjkService {
    @Override
    public List<Map<String, Object>> queryData(DataQueryInputDTO dataQueryInputDTO) throws ClassNotFoundException {
        String className = dataQueryInputDTO.getClassName();
        String url = dataQueryInputDTO.getUrl();
        String username = dataQueryInputDTO.getUsername();
        String password = dataQueryInputDTO.getPassword();
        String sql = dataQueryInputDTO.getSql();

        Class.forName(className);
        List<Map<String, Object>> result = new ArrayList<>();
        try (Connection conn = DriverManager.getConnection(url, username, password);
             Statement st = conn.createStatement();
             ResultSet resultSet = st.executeQuery(sql)) {

            ResultSetMetaData metaData = resultSet.getMetaData();
            int columnCount = metaData.getColumnCount();
            Map<String, Object> data;
            while (resultSet.next()) {
                data = new HashMap<>(columnCount);
                for (int i = 1; i <= columnCount; i++) {
                    data.put(metaData.getColumnName(i).toLowerCase(), resultSet.getObject(i));
                }
                result.add(data);
            }
        } catch (SQLException throwables) {
            throw new AppException("sql执行异常", throwables);
        }

        return result;
    }
}
